package com.czl.module_storehouse.mvp.model;

import android.text.TextUtils;
import android.util.Log;

import com.czl.base.BuildConfig;
import com.czl.base.data.net.RetrofitClient;
import com.czl.module_base.bean.CompanyBean;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.api.ApiService;
import com.czl.module_storehouse.bean.AddSupplierBean;
import com.czl.module_storehouse.bean.CityBean;
import com.czl.module_storehouse.bean.DistrictBean;
import com.czl.module_storehouse.bean.ProvinceBean;
import com.czl.module_storehouse.bean.SupplierCompanyBean;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @author by xubin,
 * @date on 2022/2/14.
 * PS: Not easy to write code, please indicate.
 */
public class SupplierModel extends BasicDataModel {
    public Observable<HttpResponse<ListBean<CompanyBean>>> selectCrmCompanyByTag(int tag, int pageNo, String companyName) {
        JSONObject object = new JSONObject();
        try {
            object.put("companyId", getManageCompanyId());
            object.put("companyTag", tag);
            object.put("pageNo", pageNo);
            object.put("companyName", companyName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody.create(mediaType, json);
        return RetrofitClient.getInstance().create(ApiService.class).selectCrmCompanyByTag(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<CompanyBean>> addCompany(AddSupplierBean bean) {
        bean.setCompanyTag(Constants.CompanyTag.TAG_SUPPLIER);
        Gson gson = new Gson();
        String json = gson.toJson(bean);
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "AddSupplierBean:" + json);
        }
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody.create(mediaType, json);
        return RetrofitClient.getInstance().create(ApiService.class).addCompany(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<CompanyBean>> addCrmCompany(String crmCompanyId) {
        JSONObject object = new JSONObject();
        try {
            object.put("companyId", getManageCompanyId());
            object.put("userId", getUserId());
            object.put("crmCompanyId", crmCompanyId);
            object.put("companyTag", Constants.CompanyTag.TAG_SUPPLIER);
            object.put("crmType", "有限责任公司");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).addCrmCompany(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<CompanyBean>> deleteCrmCompany(String crmCompanyId) {
        JSONObject object = new JSONObject();
        try {
            object.put("companyId", getManageCompanyId());
            object.put("crmCompanyId", crmCompanyId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).deleteCrmCompany(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<CompanyBean>> updateCrmCompany(SupplierCompanyBean bean) {
        //更新供应商信息
        Gson gson = new Gson();
        String json = gson.toJson(bean);
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "SupplierCompanyBean:" + json);
        }
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).updateCrmCompany(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<CompanyBean>> updateCrmCompany(AddSupplierBean addSupplierBean, CompanyBean companyBean) {
        //更新供应商信息
        addSupplierBean.setLegalPerson(null);

        addSupplierBean.setCompanyTag(Constants.CompanyTag.TAG_SUPPLIER);
        Gson gson = new Gson();
        String json = gson.toJson(addSupplierBean);
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "AddSupplierBean:" + json);
        }
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance()
                .create(ApiService.class)
                .updateCompany(RequestBody.create(mediaType, json))
                .flatMap((Function<HttpResponse<CompanyBean>, ObservableSource<HttpResponse<CompanyBean>>>) httpResponse -> {
                    if (httpResponse.isSuccess()) {
                        SupplierCompanyBean bean = new SupplierCompanyBean(companyBean, addSupplierBean,
                                getUserId(),
                                getCompanyId());
                        return updateCrmCompany(bean);
                    }
                    return Observable.error(new IOException(httpResponse.getMsg()));
                });
    }

    public Observable<HttpResponse<ListBean<ProvinceBean>>> selectProvince() {
        JSONObject object = new JSONObject();
        try {
            object.put("companyId", getManageCompanyId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).selectProvince(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<ListBean<CityBean>>> selectCity(String provinceCode) {
        JSONObject object = new JSONObject();
        try {
            object.put("provinceCode", provinceCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).selectCity(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<ListBean<DistrictBean>>> selectDistrict(String cityCode) {
        JSONObject object = new JSONObject();
        try {
            object.put("cityCode", cityCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).selectDistrict(RequestBody.create(mediaType, json));
    }

    public Observable<HttpResponse<CompanyBean>> selectByCompanyId(String companyId) {
        JSONObject object = new JSONObject();
        try {
            object.put("companyId", companyId);
            object.put("type", Constants.CompanyType.TYPE_SUPPLIER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String json = object.toString();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        return RetrofitClient.getInstance().create(ApiService.class).selectByCompanyId(RequestBody.create(mediaType, json))
                .flatMap((Function<HttpResponse<CompanyBean>, ObservableSource<HttpResponse<CompanyBean>>>) companyBeanHttpResponse -> {
                    CompanyBean responseData = companyBeanHttpResponse.getData();
                    if (responseData == null) {
                        return Observable.just(companyBeanHttpResponse);
                    }
                    String companyProvince = responseData.getCompanyProvince();
                    if (TextUtils.isEmpty(companyProvince)) {
                        return Observable.just(companyBeanHttpResponse);
                    }
                    String companyCity = responseData.getCompanyCity();
                    if (TextUtils.isEmpty(companyCity)) {
                        return getProvinces(companyBeanHttpResponse, responseData, companyProvince);
                    }
                    String companyDistrict = responseData.getCompanyDistrict();
                    if (TextUtils.isEmpty(companyDistrict)) {
                        return getProvinces(companyBeanHttpResponse, responseData, companyProvince)
                                .mergeWith(getCitys(companyBeanHttpResponse, responseData, companyProvince, companyCity));
                    }
                    return getProvinces(companyBeanHttpResponse, responseData, companyProvince)
                            .mergeWith(getCitys(companyBeanHttpResponse, responseData, companyProvince, companyCity))
                            .mergeWith(getDistrict(companyBeanHttpResponse, responseData, companyCity, companyDistrict));
                });
    }

    private Observable<HttpResponse<CompanyBean>> getCitys(HttpResponse<CompanyBean> companyBeanHttpResponse,
                                                           CompanyBean responseData, String companyProvince, String companyCity) {
        return selectCity(companyProvince)
                .map(listBeanHttpResponse -> {
                    ListBean<CityBean> data = listBeanHttpResponse.getData();
                    if (data != null && data.getList() != null) {
                        for (CityBean bean : data.getList()) {
                            if (bean.getCityCode().equals(companyCity)) {
                                responseData.setCompanyCityName(bean.getCityName());
                                break;
                            }
                        }
                    } else {
                        companyBeanHttpResponse.setState(HttpResponse.FAILED);
                        companyBeanHttpResponse.setMsg("数据请求失败");
                    }
                    return companyBeanHttpResponse;
                });
    }

    private Observable<HttpResponse<CompanyBean>> getDistrict(HttpResponse<CompanyBean> companyBeanHttpResponse,
                                                              CompanyBean responseData, String companyCity,
                                                              String companyDistrict) {
        return selectDistrict(companyCity).map(listBeanHttpResponse -> {
            ListBean<DistrictBean> data = listBeanHttpResponse.getData();
            if (data != null && data.getList() != null) {
                for (DistrictBean bean : data.getList()) {
                    if (bean.getDistrictCode().equals(companyDistrict)) {
                        responseData.setCompanyDistrictName(bean.getDistrictName());
                        break;
                    }
                }
            } else {
                companyBeanHttpResponse.setState(HttpResponse.FAILED);
                companyBeanHttpResponse.setMsg("数据请求失败");
            }
            return companyBeanHttpResponse;
        });
    }

    private Observable<HttpResponse<CompanyBean>> getProvinces(HttpResponse<CompanyBean> companyBeanHttpResponse,
                                                               CompanyBean responseData, String companyProvince) {
        return selectProvince().map(listBeanHttpResponse -> {
            ListBean<ProvinceBean> data = listBeanHttpResponse.getData();
            if (data != null && data.getList() != null) {
                for (ProvinceBean bean : data.getList()) {
                    if (bean.getProvinceCode().equals(companyProvince)) {
                        responseData.setCompanyProvinceName(bean.getProvinceName());
                        break;
                    }
                }
            } else {
                companyBeanHttpResponse.setState(HttpResponse.FAILED);
                companyBeanHttpResponse.setMsg("数据请求失败");
            }
            return companyBeanHttpResponse;
        });
    }
}
